package im.starchat.chat.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.tencent.TIMManager;
import com.tencent.av.sdk.AVError;
import com.umeng.socialize.UMShareAPI;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.ShareSDK;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.publish.PublishChooseActivity;
import im.starchat.chat.control.QavsdkControl;
import im.starchat.chat.fragment.MainTabChannelFragment;
import im.starchat.chat.fragment.MainTabLiveFragment;
import im.starchat.chat.fragment.MainTabMsgFragment;
import im.starchat.chat.fragment.MainTabProfileFragment;
import im.starchat.chat.rest.model.UserBean;
import im.starchat.chat.rest.model.api.CheckVersionResponse;
import im.starchat.chat.rest.model.api.NullResponse;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.DownloadApkManager;
import im.starchat.chat.utils.GsonUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.RetrofitErrorUtil;
import im.starchat.chat.utils.Util;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * 应用主界面
 */
public class Main2Activity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = Main2Activity.class.getSimpleName();
    private int mLoginErrorCode = AVError.AV_OK;
    private static final int DIALOG_LOGIN = 0;
    private static final int DIALOG_LOGOUT = DIALOG_LOGIN + 1;
    private static final int DIALOG_LOGIN_ERROR = DIALOG_LOGOUT + 1;

    @InjectView(R.id.tab_host)
    RadioGroup tabHost;
    private int mCurrentTabID;
    private Map<Integer, Fragment> fragmentMap = new HashMap<>();
    // 记录退出时间
    private long mExitTime;
    //    private UserInfo mSelfUserInfo;
    @InjectView(R.id.tab_publish)
    ImageView mPublishBtn;

    private ProgressDialog mDialogLogin = null;
    private ProgressDialog mDialogLogout = null;
    private QavsdkControl mQavsdkControl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.inject(this);

        //TODO cc check and download apk
        checkVersion();

        if (PreferencesStorageUtil.isUserLogin(this)) {
            getUserInfo();
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Util.ACTION_START_CONTEXT_COMPLETE);
        intentFilter.addAction(Util.ACTION_CLOSE_CONTEXT_COMPLETE);
        intentFilter.addAction(Util.ACTION_ROOM_ENTER_COMPLETE);
        intentFilter.addAction(Util.ACTION_CLOSE_ROOM_COMPLETE);
        registerReceiver(mBroadcastReceiver, intentFilter);

        mQavsdkControl = XLApplication.getQavsdkControl();
//        mSelfUserInfo = XLApplication.getMyselfUserInfo();
        startContext();

        MainTabLiveFragment mFeedFragment = MainTabLiveFragment.newInstance();//首页
        MainTabChannelFragment mPlazaFragment = MainTabChannelFragment.newInstance();//人气频道 最新入驻
        MainTabMsgFragment mMsgFragment = MainTabMsgFragment.newInstance();//消息
        MainTabProfileFragment mProfileFragment = MainTabProfileFragment.newInstance();//个人中心
        fragmentMap.put(R.id.tab_live, mFeedFragment);
        fragmentMap.put(R.id.tab_plaza, mPlazaFragment);
        fragmentMap.put(R.id.tab_message, mMsgFragment);
        fragmentMap.put(R.id.tab_personal, mProfileFragment);

        mCurrentTabID = R.id.tab_live;
        tabHost.setOnCheckedChangeListener(onCheckedChangeListener);
        ((RadioButton) findViewById(R.id.tab_live)).setChecked(true);
//        mSelfUserInfo = ((XLApplication)getApplication()).getMyselfUserInfo();
        mPublishBtn.setOnClickListener(this);

    }

    private void checkVersion() {
        XLApplication.getInstance().getRestClient().checkVersion( new Callback<CheckVersionResponse>() {
            @Override
            public void success(final CheckVersionResponse checkVersionResponse, Response response) {
                if(checkVersionResponse.isNeed_update()){
                    AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
                    if(checkVersionResponse.isForce()){
                        builder.setMessage(""+checkVersionResponse.getBody())
                                .setTitle(""+checkVersionResponse.getTitle())
                                .setPositiveButton("确认升级", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            DownloadApkManager.getInstance(Main2Activity.this).launchDownloadTool(""+checkVersionResponse.getDownload_url(),"StarChat");
                                        }
                                })
                                .setCancelable(false)
                                .create().show();
                    }else{
                        builder.setMessage(""+checkVersionResponse.getBody())
                                .setTitle(""+checkVersionResponse.getTitle())
                                .setPositiveButton("升至新版", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        DownloadApkManager.getInstance(Main2Activity.this).launchDownloadTool(""+checkVersionResponse.getDownload_url(),"StarChat");
                                    }
                                })
                                .setNegativeButton("留在旧版", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .create().show();
                    }
                }else{
                }
            }
            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(Main2Activity.this, "更新失败", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
                builder.setMessage("增加了应用升级功能;\n增加了礼物动画;\n修复了部分bug")
                        .setTitle("升级提示")
                        .setPositiveButton("确认升级", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                DownloadApkManager.getInstance(Main2Activity.this).launchDownloadTool("http://gdown.baidu.com/data/wisegame/128610b2fe4035ff/baidushoujizhushouyuan91zhu_16788605.apk","StarChat");
                            }
                        })
                        .setNegativeButton("留在旧版", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .create().show();
            }
        });
    }


    @Override
    protected void onResume() {
        Log.d(TAG, "onResume ");
        TIMManager.getInstance().init(getApplicationContext());//腾讯IM服务初始化
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
            case DIALOG_LOGIN:
                dialog = mDialogLogin = Util.newProgressDialog(this,
                        R.string.at_login);
                break;

            case DIALOG_LOGOUT:
                dialog = mDialogLogout = Util.newProgressDialog(this,
                        R.string.at_logout);
                break;

            case DIALOG_LOGIN_ERROR:
                dialog = Util.newErrorDialog(this, R.string.login_failed);
                break;

            default:
                break;
        }
        return dialog;
    }

    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            getCurrentFragment().onPause();
            Fragment fragment = fragmentMap.get(checkedId);
            if (fragment.isAdded()) {
                fragment.onResume();
            } else {
                fragmentTransaction.add(R.id.content_main, fragment);
            }
            for (Map.Entry entry : fragmentMap.entrySet()) {
                Fragment iteratorFragment = (Fragment) entry.getValue();
                if (entry.getKey().equals(checkedId)) {
                    fragmentTransaction.show(iteratorFragment);
                } else {
                    fragmentTransaction.hide(iteratorFragment);
                }
            }
            fragmentTransaction.commit();
            mCurrentTabID = checkedId;
            switch (mCurrentTabID) {
                case R.id.tab_live:
                    // 友盟统计
//                    MobclickAgent.onEvent(MainActivity.this, "2001");
                    break;
                case R.id.tab_plaza:
                    // 友盟统计
//                    MobclickAgent.onEvent(MainActivity.this, "4001");
                    break;
                case R.id.tab_personal:
                    // 友盟统计
//                    MobclickAgent.onEvent(MainActivity.this, "7001");
                    break;
            }
        }
    };

    public Fragment getCurrentFragment() {
        return fragmentMap.get(mCurrentTabID);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_publish:
                if (PreferencesStorageUtil.isStar(Main2Activity.this)) {
                    startActivity(new Intent(Main2Activity.this, PublishChooseActivity.class));
                }
                break;
        }
    }

    private boolean isFirst = true;
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
            if (action.equals(Util.ACTION_START_CONTEXT_COMPLETE)) {
                mLoginErrorCode = intent.getIntExtra(
                        Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);
                refreshWaitingDialog();
                if (mLoginErrorCode != AVError.AV_OK) {
                    Log.e(TAG, "登录失败");
                    Log.e(TAG, "startContext mLoginErrorCode mBroadcastReceiver  " + mLoginErrorCode);
                    showDialog(DIALOG_LOGIN_ERROR);
                }
                Log.d(TAG, "start context complete");
            } else if (action.equals(Util.ACTION_CLOSE_CONTEXT_COMPLETE)) {
                mQavsdkControl.setIsInStopContext(false);
            } else if (action.equals(Util.ACTION_ROOM_ENTER_COMPLETE)) {
                //进入别人的房间
                Log.d(TAG, "liveAcitivity onReceive ACTION_ROOM_CREATE_COMPLETE");
                int mCreateRoomErrorCode = intent.getIntExtra(
                        Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);
                if (isFirst) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    isFirst = false;
                }
                if (mCreateRoomErrorCode == AVError.AV_OK && !Constants.isPublish) {
                    if (Constants.getChooseRoomInfo() == null) {
//                            Toast.makeText(LiveActivity.this, "mChoseLiveVideoInfo is null !!!! ", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "LiveActivity onReceive mChoseLiveVideoInfo is " + Constants.getChooseRoomInfo());
                        return;
                    }
                    startActivity(new Intent(Main2Activity.this, AvActivity.class)
                            .putExtra(Util.EXTRA_ROOM_NUM, Constants.getChooseRoomInfo().getId()) //room id
                            .putExtra(Util.EXTRA_SELF_IDENTIFIER, Constants.getChooseRoomInfo().getUser().getId() + "")
                            .putExtra(Util.EXTRA_GROUP_ID, Constants.getChooseRoomInfo().getTencent_group_id()) // chat converse id
                            .putExtra(Util.EXTRA_PRAISE_NUM, Constants.getChooseRoomInfo().getPraises_count()));
//                    enterRoom();
                }
            } else if (action.equals(Util.ACTION_CLOSE_ROOM_COMPLETE)) {//关闭房间

            }
        }
    };

//    private void enterRoom() {
//
//        XLApplication.getInstance().getRestClient().enterRoom(Constants.getChooseRoomInfo().getId() + "", UserUtils.getUserInstance().getNickname(), new Callback<NullResponse>() {
//            @Override
//            public void success(NullResponse nullResponse, Response response) {
//
//            }
//
//            @Override
//            public void failure(RetrofitError error) {
//
//            }
//        });
//
////        new Thread() {
////            @Override
////            public void run() {
////                super.run();
////                JSONObject object = new JSONObject();
////                try {
////                    object.put(Util.EXTRA_ROOM_NUM, Constants.getChooseRoomInfo().getId());
////                    object.put(Util.EXTRA_USER_PHONE, PreferencesStorageUtil.getUserId(Main2Activity.this));
////                    System.out.println(object.toString());
////                    List<NameValuePair> list = new ArrayList<NameValuePair>();
////                    list.add(new BasicNameValuePair("viewerdata", object.toString()));
////                    String ret = HttpUtil.PostUrl(HttpUtil.enterRoomUrl, list);
////                    Log.d(TAG, "enter room" + ret);
////                } catch (JSONException e) {
////                    e.printStackTrace();
////                }
////            }
////        }.start();
//    }

    private void startContext() {
        if (!mQavsdkControl.hasAVContext()) {

//            String phone = mSelfUserInfo.getUserPhone();
//            //if (mSelfUserInfo.getLoginType() == Util.TRUSTEESHIP)
//            phone = "86-" + phone;
//            Log.e(TAG, "import phone: " + phone+ "Usersig "+ mSelfUserInfo.getUsersig());
//            mLoginErrorCode = mQavsdkControl.startContext(
//                    phone, mSelfUserInfo.getUsersig());
            mLoginErrorCode = mQavsdkControl.startContext(
                    PreferencesStorageUtil.getUserId(Main2Activity.this), PreferencesStorageUtil.getTsig(Main2Activity.this));
            Log.e(TAG, "startContext mLoginErrorCode   " + mLoginErrorCode);
            if (mLoginErrorCode != AVError.AV_OK) {
                Log.e(TAG, "startContext mLoginErrorCode   " + mLoginErrorCode);
                showDialog(DIALOG_LOGIN_ERROR);
            }
            refreshWaitingDialog();
        }
    }

    private void refreshWaitingDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Util.switchWaitingDialog(Main2Activity.this, mDialogLogin, DIALOG_LOGIN,
                        mQavsdkControl.getIsInStartContext());
                Util.switchWaitingDialog(Main2Activity.this, mDialogLogout, DIALOG_LOGOUT,
                        mQavsdkControl.getIsInStopContext());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);
        unregisterReceiver(mBroadcastReceiver);
        mQavsdkControl.stopContext();
        mQavsdkControl.setIsInStopContext(false);
    }


    private void getUserInfo() {
        XLApplication.getInstance().getRestClient().getUserInfo(PreferencesStorageUtil.getUserId(Main2Activity.this), new Callback<UserBean>() {
            @Override
            public void success(UserBean userBean, Response response) {
                if (RetrofitErrorUtil.handleResponse(Main2Activity.this, response)) {
                    return;
                }
                if (userBean != null && userBean.getAccount() != null) {
                    PreferencesStorageUtil.setDiamondCount(Main2Activity.this, userBean.getAccount().getAmount());
                }
                if (userBean != null) {
                    PreferencesStorageUtil.setUserBean(Main2Activity.this, GsonUtil.toJson(userBean));
                    PreferencesStorageUtil.setUserid(Main2Activity.this, userBean.getId());
                    if (userBean.getUser_type().equals("star")) {
                        PreferencesStorageUtil.setStar(Main2Activity.this, true);
                    } else {
                        PreferencesStorageUtil.setStar(Main2Activity.this, false);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });

    }

}
